<template>
  <el-dialog title="分配权限" :visible="dialogPowerVisible" @close="onClose">
    <el-tree
      ref="treeRef"
      v-loading="loading"
      :data="data"
      show-checkbox
      node-key="id"
      default-expand-all
      check-strictly
      :default-checked-keys="PowerArr"
      :props="defaultProps"
      @check-change="updatePowerArr"
    />
    <template #footer>
      <el-row type="flex" justify="center">
        <el-button type="primary" size="mini" @click="onClick">确认</el-button>
        <el-button type="info" size="mini" @click="onClose">取消</el-button>
      </el-row>
    </template>
  </el-dialog>
</template>

<script>
import { getSysPermission, getSysRoleId } from '@/api/role/role'
import { listTree } from '@/utils/index'
import { putSysRoleAssignPrem } from '@/api/user'
export default {
  name: 'PowerDialog',
  props: {
    dialogPowerVisible: {
      type: Boolean,
      default: false
    },
    id: {
      type: [Number, String],
      default: null
    }
  },
  data() {
    return {
      data: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      PowerArr: [],
      loading: true
    }
  },
  watch: {
    dialogPowerVisible: {
      async handler() {
        const res = await getSysPermission()
        this.data = listTree(res, 0)
      }
    },
    id: {
      async handler(id) {
        this.loading = true
        const res = await getSysRoleId(id)
        this.PowerArr = res.permIds
        this.loading = false
      }
    }
  },
  methods: {
    onClose() {
      this.$emit('update:dialogPowerVisible', false)
    },
    async onClick() {
      try {
        await putSysRoleAssignPrem({
          id: this.id,
          permIds: this.PowerArr
        })
        this.$message.success('分配权限成功')
        this.onClose()
      } catch (error) {
        console.log(error)
      }
    },
    updatePowerArr() {
      this.PowerArr = this.$refs.treeRef.getCheckedKeys()
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
